package com.example.project.controller;

import cn.hutool.core.codec.Base64Decoder;
import com.alibaba.fastjson.JSONObject;
import com.example.project.base.BaseApi;
import com.example.project.base.ConstKit;
import com.example.project.base.ResultBean;
import com.example.project.config.shiro.ShiroCacheObj;
import com.example.project.entity.TAdmin;
import com.example.project.service.TAdminService;
import com.example.project.service.impl.TAdminServiceImpl;
import com.example.project.util.MD5Utils;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/tadmin")
@Api(value = "AdminController",tags = "管理员相关接口")
public class AdminController extends BaseApi {
    @Autowired
    TAdminService tAdminService;



    @RequestMapping(value = "/test",method = RequestMethod.POST)
    @ApiOperation("测试")
    @ApiImplicitParams({
        @ApiImplicitParam(name="test",value="测试数据",required=true),
    })
    public ResultBean test(String test){

        return ok("成功",test);
    }

    @RequestMapping(value = "/getAllAdmin",method = RequestMethod.POST)
    @ApiOperation("获取所有管理员")
    public ResultBean getAllAdmin(Integer pageNo,Integer pageSize){
        try{
            PageInfo<TAdmin> list=tAdminService.getAllAdminPageInfo(pageNo,pageSize);
            return ok("成功",list);
        }catch (Exception e){
            e.printStackTrace();
            return fail("查询失败");
        }
    }

    @RequestMapping(value = "/updateAdminSort",method = RequestMethod.POST)
    @ApiOperation("获取所有管理员")
    @ApiImplicitParams({
        @ApiImplicitParam(name="pkid",required=true),
    })
    public ResultBean updateAdminSort(Integer pkid,Integer sort,String type){

        if(pkid==null){
            return fail("未获取相关参数");
        }else{
            try{
//            Integer pkid=(int)map.get("pkid");
//            Integer sort=(int)map.get("sort");
//            String type=(String) map.get("type");

//            PageInfo<TAdmin> list=tAdminService.getAllAdminPageInfo(pageNo,pageSize);
                tAdminService.updateAdminSort(pkid,sort,type);
                return ok("成功");
            }catch (Exception e){
                e.printStackTrace();
                return fail("查询失败");
            }
        }

    }

    @RequestMapping(value = "/login",method = RequestMethod.POST)
    @ApiOperation("登录")
    @ApiImplicitParams({
        @ApiImplicitParam(name="userName",required=true),
        @ApiImplicitParam(name="userPwd",required=true),
    })
    public ResultBean login(String userName,String userPwd,HttpServletResponse response){

        if(userName==null||userPwd==null){
            return fail("未获取相关参数");
        }else{
            ResultBean resultBean=new ResultBean();
            resultBean.setCode(ResultBean.FAIL);

//        userPwd= Base64Decoder.decodeStr(userPwd);

            Subject subject = SecurityUtils.getSubject();

            UsernamePasswordToken token = new UsernamePasswordToken(userName, userPwd);

            try {
                subject.login(token);
            } catch (UnknownAccountException e) {
                resultBean.setMsg("未知账户");
                return resultBean;
            } catch (IncorrectCredentialsException e) {
                resultBean.setMsg("密码不正确");
                e.printStackTrace();
                return resultBean;
            } catch (LockedAccountException e) {
                resultBean.setMsg("账户已锁定");
                return resultBean;
            } catch (ExcessiveAttemptsException e) {
                resultBean.setMsg("用户名或密码错误次数过多");
                return resultBean;
            } catch (AuthenticationException e) {
                resultBean.setMsg("用户名或密码不正确！");
                return resultBean;
            }

            if (subject.isAuthenticated()) {
                resultBean.setMsg("登录成功");
//            String key = UUIDUtils.getUUID();

//            Cookie cookie = new Cookie("code", key);
//            cookie.setMaxAge(60*60*24);
//            cookie.setHttpOnly(false);
//            cookie.setPath("/");
//            response.addCookie(cookie);
                Session session = subject.getSession();

                ShiroCacheObj obj=(ShiroCacheObj)subject.getPrincipal();

                Map<String,String> map=new HashMap(){{
                    put("auth_code",session.getId());
                    put("userNick",obj.getUserNick());
                }};
                resultBean.setCode(ResultBean.SUCCESS);
                resultBean.setData(map);

                logger.debug("登录成功：：：{}");
            } else {
                token.clear();
                resultBean.setMsg("登录失败");
            }

            return resultBean;
        }

    }

    @RequestMapping(value = "loginOut",method = RequestMethod.POST)
    @ApiOperation("退出登录")
    public ResultBean logout() {

        SecurityUtils.getSubject().logout();

        return new ResultBean();
    }
    @RequestMapping(value = "/examineUserName",method = RequestMethod.POST)
    @ApiOperation("验证登录账号重复")
    @ApiImplicitParams({
        @ApiImplicitParam(name="userName",required=true),
    })
    public ResultBean examineUserName(String userName){
        if(StringUtils.isNotEmpty(userName)){
            try{
                TAdmin tAdmin=tAdminService.queryOne(new TAdmin(){{setUserName(userName);}});
                if(tAdmin==null){
                    return ok(0);
                }else{
                    return ok(1);
                }

            }catch (Exception e){
                e.printStackTrace();
                return fail();
            }
        }else{
            return fail("未获取参数");
        }

    }
    @RequestMapping(value = "/addNewAdmin",method = RequestMethod.POST)
    @ApiOperation("添加管理员")
    @ApiImplicitParams({
        @ApiImplicitParam(name="userName",required=true),
        @ApiImplicitParam(name="userNick",required=true),
        @ApiImplicitParam(name="roleId",required=true),
    })
    public ResultBean addNewAdmin(String userName,String userNick,Integer roleId){
        if(StringUtils.isNotEmpty(userName)&&StringUtils.isNotEmpty(userNick)&&roleId!=null){
            try{
                TAdmin tAdmin=new TAdmin(){{
                    setUserName(userName);
                    setUserNick(userNick);
                    setUserPwd(MD5Utils.md5(ConstKit.DEFAULT_PWD));
                }};
                boolean one=tAdminService.addNewAdmin(tAdmin,roleId);
                if(one){
                    return ok();
                }else{
                    return fail();
                }
            }catch (Exception e){
                e.printStackTrace();
                return fail();
            }
        }else{
            return fail("未获取参数");
        }

    }
    @RequestMapping(value = "/getAdminInfoById",method = RequestMethod.POST)
    @ApiOperation("获取单个用户信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name="pkid",required=true),
    })
    public ResultBean getAdminInfoById(Integer pkid){
        if(pkid!=null && pkid>0){
            try{
                Map<String,Object> userInfo=tAdminService.getUserInfoById(pkid);

                return ok(userInfo);
            }catch (Exception e){
                e.printStackTrace();
                return fail();
            }
        }else{
            return fail("未获取参数");
        }
    }


    @RequestMapping(value = "/updateNewAdmin",method = RequestMethod.POST)
    @ApiOperation("修改管理员")
    @ApiImplicitParams({
            @ApiImplicitParam(name="pkid",required=true),
            @ApiImplicitParam(name="userName",required=true),
            @ApiImplicitParam(name="userNick",required=true),
            @ApiImplicitParam(name="roleId",required=true),
    })
    public ResultBean updateNewAdmin(TAdmin tAdmin,Integer roleId){
        if( StringUtils.isNotEmpty(tAdmin.getUserName()) && StringUtils.isNotEmpty(tAdmin.getUserNick()) && roleId>0 && tAdmin.getPkid()>0 ){
            try{
                tAdminService.updateNewAdmin(tAdmin,roleId);

                return ok();
            }catch (Exception e){
                e.printStackTrace();
                return fail();
            }
        }else{
            return fail("未获取参数");
        }

    }


    @RequestMapping(value = "/deleteByIds",method = RequestMethod.POST)
    @ApiOperation("删除管理员")
    public ResultBean deleteByIds(@RequestParam(value = "pkids") List<Integer> pkids){
        if(pkids!=null&&pkids.size()>0){
            try{
               tAdminService.deleteByIds(TAdmin.class,pkids);
                logger.debug("获取参数：：{}",pkids);
                return ok("成功");
            }catch (Exception e){
                e.printStackTrace();
                return fail("查询失败");
            }
        }else{
            return fail("未获取参数");
        }
    }
}
